package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Game;
import model.Player;

public class TakeSeatServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	public TakeSeatServlet() {
        super();
    }

 	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 		doPost(request,response);
 	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String number = request.getParameter("number");
		String name = request.getParameter("name");
		String avatar = request.getParameter("avatar");
		
		if (null == getServletContext().getAttribute("game")) {
    			
			Game game = new Game();
			
			getServletContext().setAttribute("game", game);
			
			System.out.println("The dealer has entered the table.");
		}

		Game game = (Game) getServletContext().getAttribute("game");
		int index = Integer.parseInt(number);
		
		boolean isSitted = false;
		for(int i=0; i<9; i++){
			if(game.getSeats().get(i).getPlayer() != null){
				if(request.getSession().getId() == game.getSeats().get(i).getPlayer().getSessionId()){
					isSitted = true;
				}
			}
		}
		
		if((game.getSeats().get(index-1).getPlayer() == null) && !isSitted ){
			Player p = new Player(name, request.getSession().getId(), avatar);
	    	
			game.getSeats().get(index-1).setPlayer(p);
	    	
	    	System.out.println("Player "+ number + " ("+ name +") has joined the game.");
	    	
		} else {
    		System.out.println("Failed to join the game. The seat has been taken already.");
    	}

	}

}